import numpy as np
import cv2

cap = cv2.VideoCapture(0)
ret,frame=cap.read()
ret,frame=cap.read()
r,h,c,w=10,200,10,200
track_window=(c,r,w,h)

roi=frame[r:r+h,c:c+w]      #region of interest
hsv_roi = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)    #hsv为色调，饱和度，明度
#创建一个mask,在ROI中包含所有其HSV值在指定上界和下界之间的像素
green = np.uint8([[[0,255,0 ]]])
hsv_green=cv2.cvtColor(green,cv2.COLOR_BGR2HSV)
lower_green=np.array([hsv_green[0,0,0]-30,100,100])
upper_green=np.array([hsv_green[0,0,0]+30,255,255])
#mask =cv2.inRange(hsv_roi, np.array((100.,30.,32.)),np.array((180.,120.,255.)) )
mask =cv2.inRange(hsv_roi,lower_green,upper_green )
#calcHist第一个参数为由多幅相同尺寸图像组成的数组，
#直方图尺寸为180，范围为0~180
roi_hist=cv2.calcHist([hsv_roi],[0], mask, [180],[0,180])
cv2.normalize(roi_hist, roi_hist, 0,255,cv2.NORM_MINMAX)
#定义meanshift的终止条件，10次迭代，或者如果中心至少移动了一个像素
term_crit=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,10,1)

while True:
    ret,frame = cap.read()
    if ret==True:
        hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
        #计算直方图的反投影，找到原图像(x,y)对应hist值，scale后写到dst的(x,y)位置
        dst=cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1)
        #应用meanshift找到目录的新位置
        ret,track_window=cv2.meanShift(dst,track_window,term_crit)
        #在图像上画出来
        x,y,w,h=track_window
        img2=cv2.rectangle(frame,(x,y),(x+w,y+h),255,2)
        cv2.imshow('img2',img2)
        k=cv2.waitKey(60) & 0xff
        if k==27:
            break
    else:
        break
cv2.destroyAllWindows()
cap.release()